/**
 * File name:      BeanUtil.java
 * Date:           2013-4-2
 * Description:    // 用于详细说明此程序文件完成的主要功
 *                 // 能与其他模块或函数的接口，输出值、
 *                 // 取值范围、含义及参数间的关系
 * Modify History:     Date             Programmer       Notes
 *                    ---------        ---------------  ---------
 *                    2013-4-2            胡少磊                           Initial
 **********************************************************************/
package com.wy.component.dataConvert;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;

/**
 * Created on 2013-4-2
 * <p>Title:      [模块名]</p>
 * <p>Description: [描述该类概要功能介绍]</p>
 * @version        1.0
 */
public class BeanUtil {

	   /**
     * 将一个 Map 对象转化为一个 JavaBean
     * @param type 要转化的类型
     * @param map 包含属性值的 map
     * @return 转化出来的 JavaBean 对象
     * @throws IntrospectionException
     *             如果分析类属性失败
     * @throws IllegalAccessException
     *             如果实例化 JavaBean 失败
     * @throws InstantiationException
     *             如果实例化 JavaBean 失败
     * @throws InvocationTargetException
     *             如果调用属性的 setter 方法失败
     */
    public static Object convertMap(Class type, Map map)
            throws IntrospectionException, IllegalAccessException,
            InstantiationException, InvocationTargetException {
        BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性
        Object obj = type.newInstance(); // 创建 JavaBean 对象

        // 给 JavaBean 对象的属性赋值
        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        for (int i = 0; i< propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();

            if (map.containsKey(propertyName)) {
                // 下面一句可以 try 起来，这样当一个属性赋值失败的时候就不会影响其他属性赋值。
                Object value = map.get(propertyName);

                Object[] args = new Object[1];
                args[0] = value;

                descriptor.getWriteMethod().invoke(obj, args);
            }
        }
        return obj;
    }

    /**
     * 将一个 JavaBean 对象转化为一个  Map
     * @param bean 要转化的JavaBean 对象
     * @return 转化出来的  Map 对象
     * @throws IntrospectionException 如果分析类属性失败
     * @throws IllegalAccessException 如果实例化 JavaBean 失败
     * @throws InvocationTargetException 如果调用属性的 setter 方法失败
     */
    public static Map convertBean(Object bean)
            throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        Class type = bean.getClass();
        Map returnMap = new HashMap();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);

        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        for (int i = 0; i< propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null) {
                    returnMap.put(propertyName, result);
                } else {
                    returnMap.put(propertyName, "");
                }
            }
        }
        return returnMap;
    }
    
	/**
	 * 对象序列化为字符串
	 */
	public static String serialize(Object obj) {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ObjectOutputStream objectOutputStream;
		String serStr = null;
		try {
			objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			objectOutputStream.writeObject(obj);
			serStr = byteArrayOutputStream.toString("ISO-8859-1");// 必须是ISO-8859-1
			serStr = java.net.URLEncoder.encode(serStr, "UTF-8");// 编码后字符串不是乱码（不编也不影响功能）

			objectOutputStream.close();
			byteArrayOutputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return serStr;
	}

	/**
	 * 字符串 反序列化为 对象
	 */
	public static Object unSerialize(String serStr) {
		if (serStr == null) {
			return null;
		}
		String redStr;
		Object obj = null;
		try {
			redStr = java.net.URLDecoder.decode(serStr, "UTF-8");
			ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
					redStr.getBytes("ISO-8859-1"));
			ObjectInputStream objectInputStream = new ObjectInputStream(
					byteArrayInputStream);
			obj = objectInputStream.readObject();

			objectInputStream.close();
			byteArrayInputStream.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	/**
	 * 将Bean转换为Map				               
	*/
	public static <T> Map beanToMap(T bean) {
		ObjectMapper m = new ObjectMapper();
		m.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
		return m.convertValue(bean, Map.class);
	}

	/**
	 * 将Map转换为Bean			               
	*/
	public static <T> T mapToBean(Map map, Class<T> toType) {
		ObjectMapper m = new ObjectMapper();
		return m.convertValue(map, toType);
	}

	/**
	 * 将普通List转换为有层级关系的Tree				               
	*/
	public static List<Map> listToTree(List<Map> list, String idKey,
			String pidKey) {
		return listToTree(list, idKey, pidKey, "");
	}

	/**
	 * 将普通List转换为有层级关系的Tree				               
	 */
	public static List<Map> listToTree(List<Map> list, String idKey,
			String pidKey, String root) {
		Map<Object, Map> idKeyMap = new HashMap<Object, Map>();
		for (Map map : list) {
			idKeyMap.put(map.get(idKey), map);
		}
		List<Map> treeList = new ArrayList<Map>();
		for (Map map : list) {
			// 没有父节点，表明是一级节点
			Object pid = map.get(pidKey);
			if (pid == null || pid.equals(root) || pid.equals(map.get(idKey))) {
				treeList.add(map);
			} else {
				Map parant = idKeyMap.get(pid);
				if (parant == null) {
					parant = new HashMap();
					// parant.put(idKey, pid);
					parant.put("text", pid);
					idKeyMap.put(pid, parant);
					treeList.add(parant);
				}
				if (parant.get("children") == null) {
					parant.put("children", new ArrayList());
				}
				List children = (List) parant.get("children");
				children.add(map);
			}
		}
		return treeList;
	}
}
